package com.atguigu.fink.chapter02;

import com.atguigu.fink.bean.WaterSensor;
import lombok.Data;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;

/**
 * @Author lzc
 * @Date 2022/11/28 09:06
 */
public class Flink03_Agg {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        DataStreamSource<WaterSensor> stream = env.fromElements(
            new WaterSensor("s1", 1L, 10),
            new WaterSensor("s1", 2L, 13),
//            new WaterSensor("s2", 3L, 20),
            new WaterSensor("s1", 4L, 30),
            new WaterSensor("s1", 5L, 40),
            new WaterSensor("s1", 6L, 50)
        );
        
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        Table table = tEnv.fromDataStream(stream);
        tEnv.createTemporaryView("sensor", table);
        
        // 1. table api 中使用
        // 1.1 内联用法
        table
            .groupBy($("id"))
            .select($("id"), call(MyAvg.class, $("vc")).as("avg_vc"))
            .execute()
            .print();
        
        // 1.2. 先注册再使用
        
        // 2. 在sql 中使用
        
        
    }
    
    @Data
    public static class Avg {
        public Integer sum = 0;
        public Long count = 0L;
        
    }
    
    public static class MyAvg extends AggregateFunction<Double, Avg> {
        
        // 初始化一个累加器
        // 执行次数: 1 个 key 执行一次
        @Override
        public Avg createAccumulator() {
            return new Avg();
        }
        
        // 返回最终聚和的结果
        //
        @Override
        public Double getValue(Avg acc) {
            System.out.println("acc: " + acc);
            return acc.sum * 1.0 / acc.count;
        }
        
        // 对进入的水位值进行累加的方法, 也是约定
        // 返回值: void
        // 方法名: accumulate
        // 参数列表: 参数1: 必须是累加器 参数2: 参与累加的元素
        // 来一条元素执行一次
        public void accumulate(Avg acc, Integer vc) {
            
            acc.sum += vc;
            acc.count++;
//            System.out.println(acc);
        }
        
        
    }
}
